import { useState, useEffect } from "react";
import { useHistory } from "react-router-dom";
import { Button, SearchBar } from "antd-mobile";
import { LeftOutline } from "antd-mobile-icons";
import { useDispatch, useSelector } from "react-redux";
import { clearSuggestion, getSuggestion } from "@/store/actions/search";
import { useDebounce, useDebounceFn } from "ahooks";
import { RootState } from "@/types/store";
import classNames from "classnames";
import Icon from "@/components/Icon";
import { DeleteOutline } from "antd-mobile-icons";
import style from "./index.module.scss";
const Search = () => {
  const GEEK_SEARCH_KEY = "geek_search_history";
  const [searchHistory, setSearchHistory] = useState<string[]>([]);
  useEffect(() => {
    const histories = JSON.parse(
      localStorage.getItem(GEEK_SEARCH_KEY) ?? "[]"
    ) as string;
    setSearchHistory(histories as any);
  }, []);
  const suggestion = useSelector((state: RootState) => state.search.suggestion);

  const history = useHistory();
  const [searchTxt, setSearchTxt] = useState("");
  const dispatch: any = useDispatch();
  const { run: debounceGetSuggest } = useDebounceFn(
    (value: string) => {
      dispatch(getSuggestion(value));
    },
    {
      wait: 500,
    }
  );
  const onSearchChange = (value: string) => {
    setSearchTxt(value);
    dispatch(getSuggestion(value));
    debounceGetSuggest(value);
    // 清空输入框联想关键词
    if (!value.trim()) {
      dispatch(clearSuggestion());
      return;
    }
    dispatch(clearSuggestion());
  };
  const onSearch = (value: string) => {
    dispatch(clearSuggestion());
    history.push(`/search/result?q=${value}`);
    saveHistories(value);
  };
  //   搜索历史记录
  const saveHistories = (value: string) => {
    const localHistories = JSON.parse(
      localStorage.getItem(GEEK_SEARCH_KEY) ?? "[]"
    ) as string[];
    let histories = [];

    if (localHistories.length === 0) {
      // 没有
      histories = [value];
    } else {
      // 有
      const exist = localHistories.indexOf(value) >= 0;
      if (exist) {
        // 存在
        const leftHistories = localHistories.filter((item) => item !== value);
        histories = [value, ...leftHistories];
      } else {
        // 不存在
        histories = [value, ...localHistories];
      }
    }

    localStorage.setItem(GEEK_SEARCH_KEY, JSON.stringify(histories));
  };
  // 对搜索的关键词进行高亮显示
  const highlightSuggestion = suggestion.map((item: any) => {
    if (typeof item !== "string") {
      return item;
    }
    const lowerCaseItem = item.toLocaleLowerCase();
    const lowerCaseSearchTxt = searchTxt.toLocaleLowerCase();
    const index = lowerCaseItem.indexOf(lowerCaseSearchTxt);

    const searchTxtLength = searchTxt.length;

    const left = item.slice(0, index);
    const right = item.slice(index + searchTxtLength);
    const search = item.slice(index, index + searchTxtLength);

    return {
      left,
      right,
      search,
    };
  });
  // 清空历史记录
  const onDeleteHistory = (value: string) => {
    const newSearchHistory = searchHistory.filter((item) => item !== value);
    setSearchHistory(newSearchHistory);
    localStorage.setItem(GEEK_SEARCH_KEY, JSON.stringify(newSearchHistory));
  };
  // 删除单个历史记录
  const onClearHistory = () => {
    setSearchHistory([]);
    localStorage.removeItem(GEEK_SEARCH_KEY);
  };
  return (
    // ...
    <div className={style.root}>
      <div
        className={classNames(
          "search-result",
          suggestion.length > 0 ? "show" : ""
        )}
      >
        <div
          className="result-item"
          style={{
            display: "flex",
            alignItems: "center",
            justifyContent: "space-evenly",
            margin: "10px 0",
          }}
        >
          <LeftOutline onClick={() => history.push("/home/index")} />
          <SearchBar
            style={{ width: "280px", borderRadius: "10px" }}
            placeholder="请输入内容"
            value={searchTxt}
            onChange={onSearchChange}
            className="icon-search"
          />
          <Button
            style={{
              padding: "0",
              fontSize: "12px",
              width: "40px",
              height: "30px",
              border: "none",
            }}
            onClick={() => onSearch(searchTxt)}
          >
            搜索
          </Button>
        </div>
        <div className={classNames("search-result")}>
          {highlightSuggestion.map((item: any, index: number) => (
            <div
              key={index}
              className="result-item"
              style={{
                borderBottom: "1px solid #ccc",
                height: "35px",
                display: "flex",
                alignItems: "center",
                width: "90vw",
                paddingLeft: "10px",
                marginLeft: "2vw",
              }}
              onClick={() => onSearch(item.left + item.search + item.right)}
            >
              <Icon className="icon-search" type="iconbtn_search" />
              <div className="result-value" style={{ marginLeft: "10px" }}>
                {item.left}
                {/* 放在 span 中的内容会高亮 */}
                <span style={{ color: "red" }}>{item.search}</span>
                {item.right}
              </div>
            </div>
          ))}
        </div>
        <div
          className="history"
          style={{ display: suggestion.length > 0 ? "none" : "block" }}
        ></div>
        <div className="history-list">
          <p
            style={{
              display: "flex",
              justifyContent: "space-between",
              height: "30px",
              alignItems: "center",
              borderBottom: "1px solid #ccc",
              width: "95vw",
              marginLeft: "2vw",
            }}
          >
            历史记录:
            <DeleteOutline onClick={onClearHistory} />
          </p>
          {searchHistory.map((item, index) => (
            <div
              key={index}
              className="history-item"
              style={{
                display: "flex",
                justifyContent: "space-between",
                height: "30px",
                alignItems: "center",
                borderBottom: "1px solid #ccc",
                width: "95vw",
                marginLeft: "2vw",
              }}
            >
              <span className="text-overflow">{item}</span>
              <Icon type="iconbtn_essay_close" onClick={() => onDeleteHistory(item)} />
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};
export default Search;
